

package demo9

import "fmt"
// 享元设计模式 ， 上下文中使用，有点类似服务注册，公用一个对象，对象有对象池map

type ImageFlyweightFactory struct{
	maps map[string]*ImageFlyweight
}

var imageFlyweightFactory *ImageFlyweightFactory

func GetImageFlyweightFactory() *ImageFlyweightFactory{
	if imageFlyweightFactory == nil{
		imageFlyweightFactory = &ImageFlyweightFactory{
			maps:make(map[string]*ImageFlyweight),
		}
	}
	return imageFlyweightFactory
}

func (i *ImageFlyweightFactory) Get(filename string) *ImageFlyweight{
	image := i.maps[filename]
	if image == nil {
		image = NewImageFlyweight(filename)
		i.maps[filename] = image
	}
	return image
}

type ImageFlyweight struct{
	data string
}

func NewImageFlyweight(filename string) *ImageFlyweight{
	data := fmt.Sprintf("data is iamge %s",filename)
	return &ImageFlyweight{
		data:data,
	}
}

func (i *ImageFlyweight)Data() string{
	return i.data
}

type ImageFlyweightViewer struct{
	*ImageFlyweight
}

func NewImageFlyweightViewer(filename string) *ImageFlyweightViewer{
	return &ImageFlyweightViewer{
		ImageFlyweight: GetImageFlyweightFactory().Get(filename),
	}
}

func (i *ImageFlyweightViewer)Display(){
	fmt.Println(i.Data())
}